﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using MyHelper;
using System.Timers;
using System.Xml.Xsl;
using System.Windows.Controls.Primitives;
using System.Windows.Media.Media3D;
using clf.weighing.entity;
using Button = System.Windows.Controls.Button;
using Brushes = System.Windows.Media.Brushes;
using Brush = System.Windows.Media.Brush;

namespace weighing
{
    /// <summary>
    /// CameraWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CameraWindow : GlowWindow
    {
        #region variables
        public List<CameraInfoVo>? mCameraList = new List<CameraInfoVo>();
        public CameraInfoVo? mCamerailInfoVo = new CameraInfoVo(new CameraInfo());
        private bool isEdit = false;
        private bool isEditing = false;
        #endregion

        public CameraWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }


        #region window event

        private void Camera_Window_Loaded(object sender, RoutedEventArgs e)
        {


        }

        private void Camera_Window_ContentRendered(object sender, EventArgs e)
        {
            LoadData();

        }
        #endregion

        private void LoadData()
        {
            this.DataLv.ItemsSource = null;
            var list = CameraInfoDao.Instance.GetList();
            mCameraList = list?.Select((i) => { return new CameraInfoVo(i); }).ToList();
            this.DataLv.ItemsSource = mCameraList;          
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEditing) return;
           
            isEditing = false;
            isEdit = false;
            this.DrawerHeaderTB.Text = "新增";
            this.AddDrawerRight.IsOpen = true;           
        }

        private void EditBtn_Click(object sender, RoutedEventArgs e)
        {
            isEdit = true;
            isEditing = true;
            this.DrawerHeaderTB.Text = "修改";
            Button? button = sender as Button;
            var vo = button?.Tag as CameraInfoVo;
            BindEditValue(vo?.mCameraInfo);
            mCamerailInfoVo = vo;
            this.AddDrawerRight.IsOpen = true;
         
        }

        private void DelBtn_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var vo = button?.Tag as CameraInfoVo;
            var reault = CommonFunction.Ask("是否要删除 ：" + vo?.Ip + " 摄像头");

            if (reault == MessageBoxResult.Yes)
            {
              
                var res = CameraInfoDao.Instance.Delete(vo?.mCameraInfo);

                if (res > 0)
                {
                    this.mCameraList?.Remove(vo);
                    this.DataLv.ItemsSource = null;
                    this.DataLv.ItemsSource = this.mCameraList;
                    CommonFunction.AlertInfo("操作成功");
                }
                else if (res == -1)
                {
                    CommonFunction.AlertInfo("操作失败：该分类下有数据，不能删除！");
                }
                else
                {
                    CommonFunction.AlertInfo("操作失败");
                    Growl.ErrorGlobal("操作失败");
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isEdit)
            {
                Eidt();
            }
            else
            {
                Insert();
            }
            isEdit = false;
        }

        private void Insert()
        {
            CameraInfo camera = new CameraInfo()
            {
                id = IdHelper.LongID,
                positionName = this.positionTb.Text.Trim(),
                ip = this.IpTb.Text.Trim(),
                password = this.pwdTb.Password,
                userName = this.usernameTb.Text.Trim(),
                companyId = App.CurrentCompanyVo.Id,
                clientId = App.InitConfig.clientId,
                scaleId = mCamerailInfoVo?.ScaleId,
                isDelete = 0
            };
            if(this.brandCb.SelectedIndex == -1)
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("请选择品牌");
                return;
            }

            if (RegexHelper.IsIPv4(camera.ip) ==false)
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("输入的Ip 地址不正确！");
                return;
            }

            try {
                var p =  this.portTb.Text.Trim();
                camera.port =Convert.ToInt32( p);
                if (camera.port < 0 || camera.port > 65535) {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("端口号在 0 到65535 之间");
                    return;
                }
            } catch {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("输入的端口不正确");
                return;
            }

            if (!camera.scaleId.HasValue)
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("请选择关联磅称。");
                this.ScaleCb.IsDropDownOpen = true;
                return;          
            }

            if(this.recognToB.IsChecked== true)
            {
                int index = this.DirecetionCb.SelectedIndex;
                if(index == -1)
                {
                    string msg = "必须选择识别出入类型";
                    CommonFunction.AlertInfo(msg, this);
                    this.DirecetionCb.IsDropDownOpen = true;
                    return;
                }
                camera.directionType = index;
            }               

            if (CameraInfoDao.Instance.IsExist(camera,true))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("已经存在！");
                return;
            }           
            if (this.recognToB.IsChecked == true) {
                camera.isRecognize = 1;
            }
            camera.isCapture = this.isCaptureTB.IsChecked == true ? 1 : 0;
            camera.brandType = this.brandCb.SelectedIndex + 1;
            var res = CameraInfoDao.Instance.Sqlite.Insert(camera);

            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("保存成功！");
                this.mCameraList.Insert(0, new CameraInfoVo(camera));
                this.DataLv.ItemsSource = null;
                this.DataLv.ItemsSource = mCameraList;
                ResertInput();                
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                CommonFunction.AlertInfo(msg);
            }
        }

        private void Eidt()
        {
            if (mCamerailInfoVo == null)
            {
                ResertInput();
                return;
            }
            mCamerailInfoVo.PositionName = this.positionTb.Text.Trim();
            String ip = this.IpTb.Text.Trim();
            if (RegexHelper.IsIPv4(ip)==false)
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("输入的Ip 地址不正确！");
                return;
            }
            mCamerailInfoVo.Ip = ip;

            mCamerailInfoVo.IsCapture = this.isCaptureTB.IsChecked == true ? 1 : 0;
            try
            {
                var p = this.portTb.Text.Trim();
                mCamerailInfoVo.Port = Convert.ToInt32(p);
                if (mCamerailInfoVo.Port < 0 || mCamerailInfoVo.Port > 65535)
                {
                    this.saveBtn.IsChecked = false;
                    CommonFunction.AlertInfo("端口号在 0 到65535 之间");
                    return;
                }
            }
            catch
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("输入的端口不正确");
                return;
            }

            if (this.recognToB.IsChecked == true)
            {
                int index = this.DirecetionCb.SelectedIndex;
                if (index == -1)
                {
                    string msg = "必须选择识别出入类型";
                    CommonFunction.AlertInfo(msg, this);
                    this.DirecetionCb.IsDropDownOpen = true;
                    return;
                }
                mCamerailInfoVo.DirectionType = index;
                mCamerailInfoVo.IsRecognize = 1;
            }
            else
            {
                mCamerailInfoVo.IsRecognize = 0;
            }
            string username = this.usernameTb.Text;
            if(mCamerailInfoVo.UserName!= username)
            {
                mCamerailInfoVo.UserName = username;
            }

            if (CameraInfoDao.Instance.IsExist(mCamerailInfoVo.mCameraInfo,true))
            {
                this.saveBtn.IsChecked = false;
                CommonFunction.AlertInfo("已经存在！");
                return;
            }

            if (this.recognToB.IsChecked == true)
            {
                mCamerailInfoVo.IsRecognize = 1;
            }
            mCamerailInfoVo.Password = this.pwdTb.Password;
            var res = CameraInfoDao.Instance.Sqlite.Update(mCamerailInfoVo.mCameraInfo);
            if (res > 0)
            {
                this.saveBtn.IsChecked = false;
                Growl.SuccessGlobal("保存成功！");
                isEditing = false;
                LoadData();
                ResertInput();
            }
            else
            {
                this.saveBtn.IsChecked = false;
                string msg = "保存数据失败！";
                CommonFunction.AlertInfo(msg);
            }

        }

        private void cancelBtn_Click(object sender, RoutedEventArgs e)
        {
            isEditing = false;
            this.AddDrawerRight.IsOpen = false;
        }
        /// <summary>
        /// 修改时设置值 
        /// </summary>
        private void BindEditValue(CameraInfo? camera)
        {
            if (camera == null) return;
            this.positionTb.Text = camera.positionName;
            this.IpTb.Text = camera.ip;
            this.portTb.Text = camera.port.ToString();
            this.usernameTb.Text = camera.userName;
            this.pwdTb.Password = camera.password;
            this.recognToB.IsChecked = camera.isRecognize == 1;
            if(camera.isRecognize == 1)
            {
                this.DirecetionCb.SelectedIndex = camera.directionType;
            }       
            this.brandCb.SelectedIndex = ((camera.brandType ?? 0) - 1);
            this.isCaptureTB.IsChecked = camera.isCapture == 1;           
        }

        private void ResertInput()
        {
            this.AddDrawerRight.IsOpen = false;
            this.positionTb.Text = "";
            this.IpTb.Text = "";
            this.portTb.Text = "";
            this.usernameTb.Text = "";
            this.pwdTb.Password = "";
            this.recognToB.IsChecked = false;
            this.saveBtn.IsChecked = false;
            this.ScaleCb.ItemsSource = null;
            this.isCaptureTB.IsChecked =false;
            this.brandCb.SelectedIndex = -1;
        }

 
        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void Camera_Window_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape) this.Close();
        }
        //选择关联磅称
        private void ScaleCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(this.ScaleCb.SelectedIndex > -1)
            {
                ScaleVo scale = this.ScaleCb.SelectedItem as ScaleVo;
                mCamerailInfoVo.ScaleId =scale?.Id;
            }
        }
        #region Add Drawer Opened Closed
        private void AddDrawerRight_Opened(object sender, RoutedEventArgs e)
        {
            if (isEdit)
            {
                var list = ScaleDao.Instance.GetList();
                var data = list?.Select((i) => { return new ScaleVo(i); }).ToList();
                this.ScaleCb.ItemsSource = data;
                for (int i = 0; i < list?.Count; i++)
                {
                    if(mCamerailInfoVo?.ScaleId == list[i].id)
                    {
                        this.ScaleCb.SelectedIndex = i;
                        break;
                    }
                }
            }
            else
            {
                this.ScaleCb.ItemsSource = null;
                this.ScaleCb.ItemsSource = ScaleDao.Instance.GetList()?.Select((i) => { return new ScaleVo(i); }).ToList(); ;
                if(ScaleCb.Items.Count== 1) this.ScaleCb.SelectedIndex = 0;
            }
        }

        private void AddDrawerRight_Closed(object sender, RoutedEventArgs e)
        {
            ResertInput();
        }
        #endregion

        private void BrandCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(this.brandCb.SelectedIndex > -1)
            {
                this.mCamerailInfoVo.BrandType = this.brandCb.SelectedIndex+1;
            }
        }
        #region 是否播放
      
        private void DelayUpdateVideo(CameraInfoVo vo)
        {
            Task.Delay(1000).ContinueWith(new Action<Task>(delegate {
                this.Dispatcher.Invoke(() => {
                    CommonFunction.ChangeVideoShow(vo);
                });
            }));
        }

        private void ShowOrHideBtn_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;         
            CameraInfoVo? vo = btn?.Tag as CameraInfoVo;
            if (vo?.IsPlay == 0)
            {
                string msg = $"是否要播放该视频";
                var result = CommonFunction.Ask(msg, this);
                if (result ==  MessageBoxResult.Yes)
                {
                    vo.IsPlay = 1;
                    int res = CameraInfoDao.Instance.ShowOrHide(vo.mCameraInfo);
                    if (res > 0)
                    {
                        CommonFunction.AlertInfo("操作成功，等待2秒主窗口更新。");
                        if (btn != null)
                        {
                            btn.ToolTip = "播放中，点击停止播放";
                            btn.Foreground = FindResource("DangerBrush") as Brush;
                            btn.Content = "停止";
                        }
                      
                        //延时1s 
                        DelayUpdateVideo(vo);
                    }
                    else
                    {
                        vo.IsPlay = 0;
                        CommonFunction.AlertInfo("操作失败：更新数数据失败！");                      
                    }
                }
                
            }
            else if (vo?.IsPlay == 1)
            {
                string msg = $"是否要停止播放该视频";
                var result = CommonFunction.Ask(msg, this);
                if (result == MessageBoxResult.Yes)
                {
                    vo.IsPlay = 0;
                    int res = CameraInfoDao.Instance.ShowOrHide(vo.mCameraInfo);
                    if (res > 0)
                    {
                        CommonFunction.AlertInfo("操作成功，等待主窗口更新，");
                        if(btn != null)
                        {
                            btn.ToolTip = "已停止，点击播放";
                            btn.Foreground = Brushes.Gray;
                            btn.Content = "播放";
                        }                       
                        //延时1s 
                        DelayUpdateVideo(vo);
                    }
                    else
                    {
                        vo.IsPlay = 1;
                        CommonFunction.AlertInfo("操作失败：更新数数据失败！");
                    }
                }
            }
        }
        #endregion
    }
}
